package com.vegetable.modules.controller.wx;

import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.wx.WxDepartment;
import com.vegetable.modules.service.wx.WxDepartmentService;
import com.vegetable.modules.vo.wx.UpdateUserDepartmentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 企业微信部门控制器
 * 提供部门信息查询API
 *
 * @author Qoder
 */
@Slf4j
@RestController
@RequestMapping("/wx/department")
@AllArgsConstructor
@Api(value = "企业微信部门", tags = "企业微信部门")
public class WxDepartmentController extends AbstractController {

    private final WxDepartmentService wxDepartmentService;

    /**
     * 根据系统用户ID获取用户所属部门
     */
    @SysLog(value = "根据系统用户ID获取用户所属部门")
    @GetMapping("/user/{sysUserId}")
    @ApiOperation(value = "根据系统用户ID获取用户所属部门", notes = "根据系统用户ID获取用户所属部门")
    public R<List<WxDepartment>> getSysUserDepartments(@PathVariable Long sysUserId) {
        try {
            log.info("开始获取系统用户ID {} 的所属部门", sysUserId);
            
            List<WxDepartment> departments = wxDepartmentService.getSysUserDepartments(sysUserId);
            
            log.info("获取系统用户ID {} 的所属部门完成，共 {} 个部门", sysUserId, departments.size());
            return R.data(departments, "获取成功");
        } catch (Exception e) {
            log.error("获取系统用户ID {} 的所属部门失败", sysUserId, e);
            return R.fail("获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改用户所属部门
     */
    @SysLog(value = "修改用户所属部门")
    @PostMapping("/user/updateDepartments")
    @ApiOperation(value = "修改用户所属部门", notes = "修改用户所属部门，建立系统用户与部门的关联关系")
    public R<Void> updateUserDepartments(@RequestBody UpdateUserDepartmentVO updateUserDepartmentVO) {
        try {
            log.info("开始修改系统用户ID {} 的所属部门", updateUserDepartmentVO.getSysUserId());
            log.info("接收到的参数: sysUserId={}, departmentIds={}", 
                    updateUserDepartmentVO.getSysUserId(), 
                    updateUserDepartmentVO.getDepartmentIds());
            
            wxDepartmentService.updateUserDepartments(
                updateUserDepartmentVO.getSysUserId(),
                updateUserDepartmentVO.getDepartmentIds()
            );
            
            log.info("修改系统用户ID {} 的所属部门完成", updateUserDepartmentVO.getSysUserId());
            return R.success("修改成功");
        } catch (Exception e) {
            log.error("修改系统用户ID {} 的所属部门失败", updateUserDepartmentVO.getSysUserId(), e);
            return R.fail("修改失败: " + e.getMessage());
        }
    }
}